#!/usr/bin/env python
#
# CommandThread.py
# Copyright (C) 2011 Piotr Foltyn
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import StoppableThread
import threading
import Queue


# This is an abstract class, do not instantiate it
class Command(object):
    def __init__(self):
        super(Command, self).__init__()
        self._executed = threading.Event()

    def execute(self, params):
        raise Exception, 'This method must be overridden in derived class'

    def taskDone(self):
        self._executed.set()

    def wait(self):
        self._executed.wait()


class _StopCommand(Command):
    def execute(self, ignore):
        pass


# This is an abstract class, do not instantiate it
class CommandThread(StoppableThread.StoppableThread):
    def __init__(self):
        super(CommandThread, self).__init__()
        self._commandQueue = Queue.Queue()

    def run(self):
        while not (self._stop.isSet() and self._commandQueue.empty()):
            command = self._commandQueue.get()
            self._handleCommand(command)
            self._commandQueue.task_done()

    def sendCommand(self, command):
        if not self._stop.isSet():
            self._commandQueue.put_nowait(command)

    def stop(self):
        self._stop.set()
        self._commandQueue.put_nowait(_StopCommand())

    def _handleCommand(self, command):
        raise Exception, 'This method must be overridden in derived class'
